package com.wondertek.common.dict;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wondertek.common.i18n.AutoLangUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.Collection;

/**
 * @author xqs
 */
@Slf4j
@Component
@Intercepts({
@Signature(type= ResultSetHandler.class,method = "handleResultSets",args = {Statement.class})})
public class AutoDictInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();
        try {
            if(result instanceof Page){
                ((Page<?>) result).getRecords().forEach(item -> {
                    dict(item);
                    lang(item);
                });
            }else if(result instanceof Collection<?>){
                ((Collection<?>) result).forEach(item ->{
                    dict(item);
                    lang(item);
                });
            }else {
                dict(result);
                lang(result);
            }
        }catch (Exception ex) {
            log.error("字典设置异常 {}",ex.getMessage(),ex);
        }
        return result;
    }

    private void dict(Object obj){
        AutoDictUtil.dict(obj);
    }

    private void lang(Object obj){
        AutoLangUtil.lang(obj);
    }

}
